﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Musicman.Business;
using Musicman.Common.Entities;
using System.Web.Security;


namespace MusicmanWeb
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.Cookies["remember_me"] != null && Request["action"] != "password_reset")
                {
                    User user = UserManager.Instance.LoggInUser(Request.Cookies["remember_me"]["userinfo"], Musicman.Common.Entities.LoginType.Web);
                    if (user != null)
                    {
                        this.UserName.Text = user.Emailaddress;
                        this.Password.Attributes.Add("value", user.Password);
                        this.rememberme.Checked = true;
                    }
                }

                if (Request["action"] == "password_reset")
                {
                    string code = Request["activationcode"];
                    Guid aCode = new Guid(code);
                    if (UserManager.Instance.ResetUserPassword(aCode))
                    {
                        this.MessageInfo.Text = "Your passwrod is successfully reset. You can try to log in with your new password";
                    }
                    else
                    {
                        this.MessageInfo.Text = "Erorr reseting password";
                    }
                }
            }
        }

        protected void Login_Click(object sender, EventArgs e)
        {
            User user = UserManager.Instance.LoggInUser(this.UserName.Text, this.Password.Text, Musicman.Common.Entities.LoginType.Web);
            if (user != null)
            {
                if (this.rememberme.Checked)
                {
                    Response.Cookies["remember_me"]["userinfo"] = Server.HtmlEncode(user.Password);
                    Response.Cookies["remember_me"].Expires = DateTime.Today.AddMonths(1);
                }
                else
                {
                    if (Request.Cookies["remember_me"] != null)
                    {
                        Response.Cookies["remember_me"].Expires = DateTime.Now.AddDays(-1);
                    }
                }
                Session["UserID"] = user.Personid;
                FormsAuthentication.SetAuthCookie(user.Personid.ToString(), false);

                FormsAuthentication.RedirectFromLoginPage(user.Personid.ToString(), true);
            }
        }
    }
}
